package cn.com.lyj6851.common.validate;

import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.context.request.ServletWebRequest;

import cn.com.lyj6851.common.validate.code.ValidateCode;
import cn.com.lyj6851.common.validate.code.ValidateCodeException;
import cn.com.lyj6851.common.validate.code.ValidateCodeGenerator;
import cn.com.lyj6851.common.validate.code.ValidateCodeProcessor;
import cn.com.lyj6851.common.validate.code.ValidateCodeRepository;
import cn.com.lyj6851.common.validate.code.ValidateCodeType;

public abstract class AbstractValidateCodeProcessor<C extends ValidateCode> implements ValidateCodeProcessor {

	/**
     * 收集系统中所有的 {@link ValidateCodeGenerator} 接口的实现。
     */
    @Autowired
    private Map<String, ValidateCodeGenerator> validateCodeGenerators;

    @Autowired
    private ValidateCodeRepository validateCodeRepository;
    
    /**
     * 如何发送校验码，由子类实现
     * 是发送到浏览器;还是发送到手机 短信验证码
     * @param request
     * @param validateCode
     * @throws Exception
     */
    protected abstract void send(ServletWebRequest request, C validateCode) throws Exception;
	
    /**
     * 创建验证码
     *
     * @param request
     * @throws Exception
     */
	@Override
	public void create(ServletWebRequest request) throws Exception {
		C validateCode = generate(request); //创建
        save(request, validateCode); //存储
        send(request, validateCode); //发送
	}

	@SuppressWarnings("unchecked")
	@Override
	public void validate(ServletWebRequest request) {
		ValidateCodeType codeType = getValidateCodeType(request);
		// 从存储中获取code
        C codeInSession = (C) validateCodeRepository.get(request, codeType);

        String codeInRequest;
        try {// 从请求参数中获取code
            codeInRequest = ServletRequestUtils.getStringParameter(request.getRequest(),
                    codeType.getParamNameOnValidate());
        } catch (ServletRequestBindingException e) {
            throw new ValidateCodeException("获取验证码的值失败");
        }

        if (StringUtils.isBlank(codeInRequest)) {
            throw new ValidateCodeException(codeType + "验证码的值不能为空");
        }

        if (codeInSession == null) {
            throw new ValidateCodeException(codeType + "验证码不存在");
        }

        if (codeInSession.isExpried()) {
            validateCodeRepository.remove(request, codeType);
            throw new ValidateCodeException(codeType + "验证码已过期");
        }
        // 请求参数获取的与存储的比较;
        if (!StringUtils.equals(codeInSession.getCode(), codeInRequest)) {
            throw new ValidateCodeException(codeType + "验证码不匹配");
        }

        validateCodeRepository.remove(request, codeType);
		
	}

	/**
     * 保存校验码
     *
     * @param request
     * @param validateCode
     */
    private void save(ServletWebRequest request, C validateCode) {
        // 只将验证码的验证码和过期时间存入session
        ValidateCode code = new ValidateCode(validateCode.getCode(), validateCode.getExpireTime());
        // 调用实现类;是保存到redis还是服务器session中
        validateCodeRepository.save(request, code, getValidateCodeType(request));
    }
	 /**
     * 生成校验码
     *
     * @param request
     * @return
     */
    @SuppressWarnings({ "unchecked" })
    private C generate(ServletWebRequest request) {
    	
        String type = getValidateCodeType(request).toString().toLowerCase();
        String generatorName = type + ValidateCodeGenerator.class.getSimpleName();
        // 从验证码实例类收集器获取对应的实现类
        ValidateCodeGenerator validateCodeGenerator = validateCodeGenerators.get(generatorName);
        if (validateCodeGenerator == null) {
            throw new ValidateCodeException("验证码生成器" + generatorName + "不存在");
        }
        return (C) validateCodeGenerator.generate(request);
    }
    /**
     * 根据实现类的名称节取字符串
     * @param request
     * @return
     */
    private ValidateCodeType getValidateCodeType(ServletWebRequest request) {
        String type = StringUtils.substringBefore(getClass().getSimpleName(), "ValidateCodeProcessor");
        return ValidateCodeType.valueOf(type.toUpperCase());
    }
}
